<template>
  <div class="container">
    <div v-infinite-scroll="load" :infinite-scroll-immediate="false" infinite-scroll-delay="200"
      :infinite-scroll-distance="400">
      <vantSearch v-model="value" shape="round" background="#71e8c0" @search="onSearch"
        placeholder="请输入搜索关键词" />
      <VantTabs id="vanttabs" v-model:active="active" sticky swipeable title-active-color="#ff6347"
        color="#ff6347" ref="vanttabs" :lazy-render="false" @change="changeTab">
        <div v-for="(tag,index) in worksTags" :key="index">
          <VantTab :title="tag">
            <!-- 作品列表 -->
            <water-fall v-if="currentKeyWord==tag" :data="data.data" :gutter="5">
              <template #item="{item}">
                <el-image fit="scale-down" class="img" :src="minioUrl+item.fimg"
                  @click.stop="preview(item.id,item.title,item.fimg)">
                  <template #error>
                    <div class="image-slot">

                    </div>
                  </template>
                </el-image>
                <div class="bottom">
                  <div v-html="brightenKeyword (item.title )" class="title"
                    @click.stop="preview(item.id,item.title,item.fimg)">
                  </div>
                  <div class="head">
                    <el-avatar :size="20" :src="item.headImg" />
                  </div>
                  <div class="username">{{item.nickName}}</div>
                  <div class="like">
                    <span v-bind:class="['tulin',{'tulin-like':item.isLike}]"
                      @click="cancelLike(item.id,item)"></span>
                    <span v-bind:class="['tulin',{'tulin-unlike':!item.isLike}]"
                      @click="like(item.id,item)"></span>
                    <!-- <span class="tulin tulin-like" @click="cancelLike(item.id)"></span> -->
                    <div class="count">{{likeFormat1(item.likeCount)}}
                    </div>
                  </div>
                </div>
              </template>
            </water-fall>
          </VantTab>
        </div>
      </VantTabs>
    </div>
    <div class="loading" v-loading="loading"></div>
    <el-divider v-show="!loading">
      这里没有更多啦~
    </el-divider>
  </div>

</template>

<script>
import { Tab, Tabs, Search } from 'vant';
import WaterFall from '../../components/WaterFall.vue';
import { minioUrl } from "../../base/index";
import { likeFormat } from '../../utils/index';
export default {
  name: 'GWorks',
  components: {
    WaterFall, VantTab: Tab, VantTabs: Tabs, VantSearch: Search,
  },
  data () {
    return {
      active: 0,
      loading: true,
      value: "",
      worksTags: ["推荐", "旅游", "影视", "摄影"],
      data: [
      ],
      //各类标签搜索页码缓存，这样保证每次请求都是不同页，保证数据不重复
      searchData: [
        {
          keyword: "推荐",
          pageNum: 1,
          pageSize: 10,
        }
      ],
      //当前关键词(搜索标签)
      currentKeyWord: "推荐",
      pageNum: 1,
      minioUrl,
    };
  },
  beforeRouteEnter (to, from, next) {
    //如果是从详情页面返回 就使用缓存的作品列表
    if (from.name === "作品详情") {
      to.meta.keepAlive = true;
    } else {
      to.meta.keepAlive = false;
    }
    next();
  },
  mounted () {
    this.load();
    //获取热门标签
    this.getWorksHotTags();

  },
  methods: {
    load () {
      // 不使用搜索缓存
      this.getWorksSearchs(this.currentKeyWord, this.pageNum++, 10);
      //使用搜索缓存
      // this.storageSearch();
    },
    // 使用搜索缓存==>获取搜索条件
    storageSearch () {
      // 如果已经存在搜索历史,就获取此标签的已经浏览后的页码
      for (var key in this.searchData) {
        if (this.currentKeyWord == this.searchData[key].keyword) {
          this.getWorksSearchs(this.currentKeyWord, this.searchData[key].pageNum++, this.searchData[key].pageSize);
          return;
        }
      }
      //其他情况，添加入搜索历史
      this.searchData.push({ keyword: this.currentKeyWord, pageNum: 2, pageSize: 10 })
      this.getWorksSearchs(this.currentKeyWord, 1, 10);
    },
    getWorksSearchs (keyWord, pageNum, pageSize) {
      this.$axios.get("/works/" + keyWord + "/" + pageNum + "/" + pageSize + "").then(res => {
        if (res.flag) {
          if (res.data.data.length < pageSize) {
            this.loading = false;
          } else {
            this.loading = true;
          }
          if (this.data.keyword == res.data.keyword) {
            for (var key in res.data.data) {
              this.data.data.push(res.data.data[key]);
            }
          } else {
            this.data = res.data;
          }
        }
      });
    },
    //搜索功能
    onSearch (val) {
      this.flag = true;
      if (val.length > 6) {
        val = val.substring(0, 5) + "..."
      }
      this.data = [];
      this.currentKeyWord = val;
      this.pageNum = 1;
      //如果导航标签已经有搜索的关键词
      for (var i = 0; i < this.worksTags.length; i++) {
        if (val == this.worksTags[i]) {
          this.active = i;
          this.flag = false;
        }
      }
      //没有就添加导航标签
      if (this.flag) {
        this.active = 1;
        this.worksTags.splice(1, 0, val);
      }
      this.load();
    },
    changeTab (name, title) {
      console.log("works=>changeTab");
      this.currentKeyWord = title;
      this.pageNum = 1;//不使用缓存搜索时加
      this.load();
    },
    changeTab1 (e) {
      console.log("works=>changeTab");
      this.currentKeyWord = e.title;
      this.pageNum = 1;//不使用缓存搜索时加
      this.load();
    },
    //获取作品标签
    getWorksHotTags () {
      this.$axios("/works/hottags").then(res => {
        if (res.flag) {
          for (var key in res.data) {
            this.worksTags.push(res.data[key].name);
          }
        }
      })
    },
    //查看作品详情
    preview (id, title, fimg) {
      console.log(title);
      //加入历史记录
      this.$axios.post("/lookhistory", {
        "worksId": id,
        "worksTitle": title,
        "worksFImg": fimg
      }).then(res => {
        console.log("添加历史记录-wokrs-preview", res);
      })
      //跳转详情
      this.$router.push({ name: '作品详情', params: { worksId: id } });
    },

    like (workId, item) {
      this.$axios.post("/like/" + workId + "/1").then(res => {
        if (res.flag) {
          item.isLike = true;
          item.likeCount += 1;
        }
      })
    },
    // 高亮搜索词
    brightenKeyword (val) {
      if (this.currentKeyWord == "推荐") {
        return val;
      }
      let res = val;
      var keywordarr = this.currentKeyWord.split("");
      for (var key in keywordarr) {
        if (val) {
          const Reg = new RegExp(`${keywordarr[key]}(?!([^<img]*[/(.*?)>]|[^<video]*[/video>]|[^<audio]*[/audio>]))`, 'i');
          res = res.replace(Reg, `<span style="color: red;">${keywordarr[key]}</span>`);
        }
      }
      return res;
    },
    cancelLike (workId, item) {
      this.$axios.delete("/like/" + workId + "/1").then(res => {
        if (res.flag) {
          item.isLike = false;
          item.likeCount -= 1;
        }
      })
    },
    likeFormat1 (num) {
      return likeFormat(num);
    },
  },
  watch: {
    tabChangeWatch (old, newElement) {
      console.log(old);
      console.log(newElement);
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background-color: #f2f3f8;
}

.container {
  margin-bottom: 30px;
  .loading {
    height: 30px;
  }
}

.img {
  border-radius: 5px;
  max-height: 300px;
}
.bottom {
  padding: 0px 10px 0px 10px;
  height: 30px;
  // background-color: black;
  .title {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; // 2行
  }
  .head {
    float: left;
    margin-top: 5px;
    margin-right: 3px;
  }
  .username {
    float: left;
    font-size: 13px;
    line-height: 30px;
    width: 40%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
  .like {
    float: right;
    margin-top: 4px;
    .tulin-unlike,
    .tulin-like {
      float: left;
      font-size: 20px;
    }
    .count {
      margin-top: 4px;
      float: left;
      font-size: 12px;
    }
  }
}
.halo-btn {
  margin: 100px auto;
  display: block;
}
</style>